package cn.hdu.liang.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

class ExamFib2 implements Callable<String> {

    private final int n;

    public ExamFib2(int n) {
        this.n = n;
    }

    private String getFib(int n) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < n; i++) {
            sb.append(fib(i));
        }
        return sb.toString();
    }

    private int fib(int n) {
        if(n < 2) {
            return 1;
        }
        return fib(n - 2) + fib(n - 1);
    }

    @Override
    public String call() throws Exception {
        return getFib(n);
    }
}

public class Exam5 {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        Random random = new Random(System.currentTimeMillis());
        List<Future<String>> list = new ArrayList<>(100);
        for(int i = 0; i < 100; i++) {
            list.add(exec.submit(new ExamFib2(random.nextInt(40))));
        }
        for(Future<String> fs : list) {
            try {
                System.out.println(fs.get());
            } catch(InterruptedException | ExecutionException e) {
                e.printStackTrace();
            } finally {
                exec.shutdown();
            }
        }
        System.out.println("Main函数结束");
    }
}
